import { WinstonModule } from 'nest-winston';
import { createLogger, format } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

const formats = format.combine(format.timestamp({ format: 'YYYY/MM/DD HH:mm:ss' }), format.json(), format.prettyPrint());

const dailyTransportOptions: DailyRotateFile.DailyRotateFileTransportOptions = {
  dirname: 'logs',
  filename: '%DATE%.log',
  datePattern: 'YYYY-MM-DD',
  zippedArchive: true,
  maxFiles: '14d',
  maxSize: '20m',
};

const dailyInfoFileTransports = new DailyRotateFile({
  ...dailyTransportOptions,
  dirname: 'logs/info',
  level: 'info',
});

const dailyErrorFileTransports = new DailyRotateFile({
  ...dailyTransportOptions,
  dirname: 'logs/error',
  level: 'error',
});

const dailyDebugFileTransports = new DailyRotateFile({
  ...dailyTransportOptions,
  dirname: 'logs/debug',
  level: 'debug',
});

const dailyAccessFileTransports = new DailyRotateFile({
  ...dailyTransportOptions,
  dirname: 'logs/access',
  level: 'http',
});

const dailyExceptionsTransports = new DailyRotateFile({
  ...dailyTransportOptions,
  dirname: 'logs/exceptions',
});

export const instance = createLogger({
  format: formats,
  transports: [dailyErrorFileTransports, dailyInfoFileTransports, dailyDebugFileTransports, dailyAccessFileTransports],
  exceptionHandlers: [dailyExceptionsTransports],
  rejectionHandlers: [dailyExceptionsTransports],
  handleExceptions: true,
  handleRejections: true,
});

export const logger = WinstonModule.createLogger({
  instance,
});
